/**
 * 正则校验
 * @param {*} fn express-validator 验证中间件函数 body query param 等
 * @param {*} name 验证字段名
 * @param {*} reg 正则表达式
 * @returns Validation Chain
 */
const validReg = (fn, name, reg) => {
  if (typeof fn !== 'function' || !name || !(reg instanceof RegExp)) return []

  return fn(name)
    .if(fn(name).exists().notEmpty())
    .custom(value => {
      return reg.test(value)
    })
    .withMessage(`${name} 格式错误`)
}

// 整数验证
const validInt = (fn, name) => {
  return validReg(fn, name, /^\d+$/)
}

// 数字验证
const validNumber = (fn, name) => {
  return validReg(fn, name, /^\d+.\d+$/)
}

// 账号校验
const accountReg = /^[\da-zA-Z]+$/

module.exports = {
  validReg,
  validInt,
  validNumber,
  accountReg
}
